$(document).ready(function() {

	$('#admin_filter_open').click(function(evt) {
		var w_width = $(window).width();
		var w_height = $(document).height();
		var left = (w_width - $('.admin_filter').width()) / 2;

		if (left < 0)
			left = left * -1;
		
		$('.admin_filter').css('left', left);
		
		$('#admin_bar').css('width', w_width);
		$('#admin_bar').css('height', w_height);

		$('#admin_bar').fadeTo('slow', 0.6);
		$('.admin_filter').delay(800).slideDown('slow');

		evt.preventDefault();
	});
	
	$('#admin_filter_close').click(function(evt) {
		$('.admin_filter').slideUp('slow');
		$('#admin_bar').delay(500).fadeOut('slow');

		evt.preventDefault();
	});

	$('.help').tooltip({
		position: {
			my: 'right top', at: 'right bottom', collision: 'flipfit'
		}
	});

	$('body').keypress(function (evt) {
		if (evt.keyCode == 27) { //escape
			if ($('.admin_filter').is(':visible')) {
				$('.admin_filter').slideUp('slow');
				$('#admin_bar').delay(500).fadeOut('slow');
			}
		}	
	});
	
	var menu = 0;
	
	$('.admin_extra_actions').click(function() {
		if (window.getSelection) {
			window.getSelection().removeAllRanges();
		}

		menu = $(this).find('ul');
		
		if ($(menu).is(':visible')) {
			$(menu).fadeOut(400);
		} else {
			var pos = $(this).position();
			
			$(menu).css('top', pos.top + $(this).height() / 2);
			$(menu).css('left', pos.left + $(this).width() - $(menu).width());
			$(menu).fadeIn(200);
			$(menu).removeClass('out');
		}
		
	});
	
	$('.admin_extra_actions').mouseout(function() {
		$(menu).addClass('out');
	});
	
	$(document).click(function() {
		$('.out').hide();
	});

	$(document).ajaxError(function(evt, request, opt, error) {
		alert(error);
	});

});

function addHover(element) {
	$(element).addClass('hover');
}

function removeHover(element) {
	$(element).removeClass('hover');
}

function checkAll() {
	if ($('#admin_list_batch_checkbox').is(':checked'))
		$('.admin_batch_checkbox').attr('checked', 'checked');
	else
		$('.admin_batch_checkbox').removeAttr('checked');

	return true;
}

function createDeleteForm(data) {
	if (confirm(data.message)) {
		var f = $('<form></form>');

		$(f).css('display', 'none');
		$(f).attr('id', 'deleteForm');
		$(f).attr('method', 'post');
		$(f).attr('action', data.url);

		$('<input type="hidden">').attr({
			name: 'sf_method',
			value: 'delete'
		}).appendTo($(f));

		if (data.isCSRFProtected)
		{
			$('<input type="hidden">').attr({
				name: data.CSRFFieldName,
				value: data.CSRFToken,
			}).appendTo($(f));
		}

		$('<input type="hidden">').attr({
			name: data.fieldName,
			value: data.fieldValue,
		}).appendTo($(f));

		$(f).appendTo('body');
		$(f).submit();
	}

	return false;
}